package com.ziyueyuwen.xiniao.base.handler;

import com.alibaba.fastjson.JSON;
import com.suyeer.basic.util.HttpResUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import static com.ziyueyuwen.xiniao.base.BaseUtil.saveErrorMsgAndData;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveSuccessMsgAndData;

/**
 * @author wancheng  on 2018/12/23.
 */
@RestController
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static Integer BIND_ERROR_CODE = 501;

    /**
     * 参数校验异常处理
     *
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    public void exceptionHandler(HttpServletRequest request,
                                 HttpServletResponse response,
                                 BindException ex) {

        HttpResContent<BindExceptionResponseData> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("参数校验");
        try {
            String url = request.getRequestURI();
            StringBuilder errorMessage = new StringBuilder("url:");
            errorMessage.append(url);
            errorMessage.append(" 详情:");
            errorMessage.append(ex.getFieldErrors()
                    .stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining(",")));
            throw new Exception(errorMessage.toString());
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }

    }

}
